<?php

/**
 * @author lzp300
 * @copyright 2015-03-26
 */

class osiiOrder extends actionAbstract{
    
    /**
     * 构造函数
     * @var array
     */
    function __construct() {
        parent::__construct();
	    set_time_limit(60);
    }
    
    /**
     * 权限MD5加密
     *   Key //luo2b//uni1001        ID //luo2b  //unibooking
     */
    function SignUtil($serviceName="DomesticSubmitNewHotelOrder",$accountKey="luo2b",$version="1.1.0",$accountID="luo2b"){
        $reqTime=date('Y-m-d',time());
        
        $resuoce=array();
        $originalArray=array();
        
        $originalArray['Version']=$version;
        $originalArray['AccountID']=$accountID;
        $originalArray['ReqTime']=$reqTime;
        $originalArray['ServiceName']=$serviceName;
        ksort($originalArray);
        $sortedArray="";
        foreach($originalArray as $k=>$v){
            $sortedArray.=$k.'='.$v.'&';
        }
        $sortedArray=trim($sortedArray,'&');
        $keywords=md5($sortedArray.$accountKey);
        $resuoce['version']=$version;
        $resuoce['accountId']=$accountID;
        $resuoce['serviceName']=$serviceName;
        $resuoce['sign']=$keywords;
        $resuoce['reqTime']=$reqTime;
        //echo "<pre>";print_r($resuoce);exit;
        
        return $resuoce;
    }
    
    function returnHead($status,$responseCode,$responseDescription){
        $resuoce=array();
        $resuoce['status']=$status;
        $resuoce['responseCode']=$responseCode;
        $resuoce['responseDescription']=$responseDescription;
        
        return $resuoce;
    }
    /**
     * 公共调用
     */
    function thall(){
        header("Content-type:text/html;charset=utf-8");
        $arr=$GLOBALS['HTTP_RAW_POST_DATA'];
        
        $arr=json_decode($arr,true);
        
        foreach($arr as $k=>$v){
            if(is_object($v)){
                $arr[$k]=(array)$v;
            }
        }
        //echo "<pre>";print_r($arr);exit;
        $head = $arr['head'];   $body = $arr['body'];
        
        if(empty($head)||empty($body)){
            $errohead=$this->returnHead(4,4000,"报文错误");
            
            $logs="返回数据：".json_encode($errohead)."\r\n接收数据：".json_encode($arr);
            $this->setLogs($logs);
            
            echo json_encode(array("head"=>$errohead,"body"=>""));exit;
        }else{
            $myHead=$this->SignUtil($head['serviceName']);
            //print_r($myHead);exit;
            if(array_diff($myHead,$head)){
                $errohead=$this->returnHead(9,4002,"签名验证错误");
                
                $logs="返回数据：".json_encode($errohead)."\r\n接收数据：".json_encode($arr);
                $this->setLogs($logs);
                
                echo json_encode(array("head"=>$errohead,"body"=>""));exit;
            }else{
                $apiName=array("DomesticCheckRoomAvail","DomesticSubmitNewHotelOrder","DomesticCancelHotelOrder","DomesticGetOrderStatus","PushOrder");
                if(in_array($head['serviceName'],$apiName)){
                    $thall_code = $this->$head['serviceName']($body,$arr);
                    //print_r($thall_code);exit;
                    
                    $logs="调用方法：".$head['serviceName']."\r\n返回数据：".json_decode(json_encode($thall_code))."\r\n接收数据：".json_encode($arr);
                    $this->setLogs($logs);
                    
                    echo $thall_code;exit;
                }else{
                    $errohead=$this->returnHead(9,9010,"服务名称错误或尚未提供指定服务");
                    
                    $logs="返回数据：".json_encode($errohead)."\r\n接收数据：".json_encode($arr);
                    $this->setLogs($logs);
                    
                    echo json_encode(array("head"=>$errohead,"body"=>""));exit;
                }
            }
        }
    }
    
    /**
     * 可订检查接口
     */
    function DomesticCheckRoomAvail($body,$array){
        $arr=array();
        $arr['body']['availQuantity'] = 0;
        $arr['body']['resultCode'] = 0;
        $arr['body']['resultDescript'] = '不可定';
        
        $arr['head']['status'] = 0;
        $arr['head']['responseCode'] = '0000';
        $arr['head']['responseDescription'] = '查询成功';
        
        if(empty($body['hotelCode'])||empty($body['roomTypeCode'])||empty($body['arrivalDate'])||empty($body['departureDate'])||empty($body['roomNumber'])){
            $arr['head']['status'] = 2;
			$arr['head']['responseCode'] = 2000;
			$arr['head']['responseDescription'] = '数据错误';
			
			return json_encode(array("head"=>$arr['head'],"body"=>$arr['body']));
        }else{
            $rooms = $this->selectRooms($body['hotelCode'],$body['roomTypeCode'],strtotime($body['arrivalDate']),strtotime($body['departureDate']));
            if($rooms&&$body['roomNumber']<=$rooms){
                $arr['body']['availQuantity'] = $rooms;
                $arr['body']['resultCode'] = 1;
                $arr['body']['resultDescript'] = '可定';
                
                $arr['head']['status'] = 0;
                $arr['head']['responseCode'] = '0000';
                $arr['head']['responseDescription'] = '查询成功';
            }else{
                $arr['body']['availQuantity'] = $rooms;
                $arr['body']['resultCode'] = 0;
                $arr['body']['resultDescript'] = '不可定';
                
                $arr['head']['status'] = 0;
                $arr['head']['responseCode'] = '0000';
                $arr['head']['responseDescription'] = '查询成功';
            }
            
            return json_encode($arr);
        }
        
    }
    
    /**
     * 新订订单接口
     */
    function DomesticSubmitNewHotelOrder($body,$array){
        $this->loadModel('pms','orders');
        $this->loadModel('hotel','category');
        $this->loadModel('hotel','type');
        
        $arr['head']['status'] = 0;
        $arr['head']['responseCode'] = '0000';
        $arr['head']['responseDescription'] = '操作成功';
        $rooms=0;
        if(!empty($body['hotelCode'])&&!empty($body['roomTypeId'])&&!empty($body['effectDate'])&&!empty($body['departure'])&&!empty($body['quantity'])&&!empty($body['orderID'])&&!empty($body['sourceID'])){
            $rooms = $this->selectRooms($body['hotelCode'],$body['roomTypeId'],strtotime($body['effectDate']),strtotime($body['departure']));
            $setprice=$this->setPrice($body['hotelCode'],$body['roomTypeId'],strtotime($body['effectDate']),strtotime($body['departure']),$body['sourceID'],$body['costAmount'],$body['orderID'],$body['quantity'],$body['balanceType'],isset($body['price'])?$body['price']:0);
        }
		if($rooms){
			$data['orderId']    =   $body['orderID'];
			$data['hotelId']    =   $body['hotelCode'];
			$data['roomId']     =   $body['roomTypeId'];
			$data['startDate']  =   strtotime($body['effectDate']);
			$data['endDate']    =   strtotime($body['departure']);
			
			$data['price']      =   $setprice;
			$name = '';
			foreach($body['guests'] as $k=>$v){
				if(!empty($v['chinesName'])){
					if($k == 0){
						$name .= $v['chinesName'];
					}else{
						$name .= ','.$v['chinesName'];
					}
				}else{
					if($k == 0){
						$name .= $v['lastName'];
					}else{
						$name .= ','.$v['lastName'];
					}
				}
			}
			$data['type']       =   $body['sourceID'];//渠道编号
			$data['name']       =   $name;//客户姓名
			$data['mobile']     =   $body['mobilePhone'];
			$data['latestTime'] =   0;
			$data['remark']     =   '';//订单备注
			$data['countRoom']  =   $body['quantity'];//房间总数
			$data['created']    =   time();//订单生成时间
			$data['protime']    =   time();//操作时间
			$data['payType']    =   $body['balanceType'];
			$data['paid']       =   $body['balanceType']=="PP"?$setprice:0;
			//获取该时间段的总价
			$gainPrice=$this->gainPrice($body['hotelCode'],$body['roomTypeId'],strtotime($body['effectDate']),strtotime($body['departure']));
			$data['thPrice']    =   $gainPrice;
			
			if($rooms&&$body['quantity']<=$rooms&&!isset($body['orderStatus'])){
				$data['status']     =   1;//订单状态
				
				$arr['body']['returnCode'] = 0;
				$arr['body']['returnDescript'] = '预订成功';
				$arr['body']['orderStatus'] = 3;
				$arr['body']['interFaceAmount'] = $body['costAmount'];
				
			}elseif($rooms&&$body['quantity']<=$rooms&&isset($body['orderStatus'])&&$body['orderStatus']=='66'){
				$arr['body']['returnCode'] = 0;
				$arr['body']['returnDescript'] = '预订成功';
				$arr['body']['orderStatus'] = 66;
				$arr['body']['interFaceAmount'] = $body['costAmount'];
				
				$data['status']=66;//待支付
			}else{
				$arr['body']['returnCode'] = 0;
				$arr['body']['returnDescript'] = '已发送';
				$arr['body']['orderStatus'] = 1;
				$arr['body']['interFaceAmount'] = 0;
				$arr['body']['hotelConfirmNo']=0;
				
				$data['status']     =   0;//订单状态
			}
			
			//判断订单是否存在
			$qunaer_order=$this->pms->ordersModel->fetchRow("select id from pms_orders where orderId='".$body['orderID']."' and hotelId='".$body['hotelCode']."' and type='".$body['sourceID']."' and roomId=".$body['roomTypeId']);
			if($qunaer_order){
				$res = $this->pms->ordersModel->update($data,"id=".$qunaer_order['id']);
			}else{
				$res = $this->pms->ordersModel->insert($data);
			}
			
			if($res){
				if($data['status']==1||$data['status']==66){
					if(!$qunaer_order){
						//已用房间量修改
						$this->lockRoomstaus($body['roomTypeId'],strtotime($body['effectDate']),strtotime($body['departure']),$body['quantity'],$body['hotelCode']);
					}
				}
				
				//短信发送
				$hotelTh=$this->hotel->categoryModel->fetchRow("select hotelName,phone from hotel_category where id=".$body['hotelCode']);
				$roomName=$this->hotel->typeModel->fetchRow("select title from hotel_type where id=".$body['roomTypeId']);
				$mobile=trim($hotelTh['phone']);
				$is_order_day=(strtotime($body['departure'])-strtotime($body['effectDate']))/24/3600;
				
				$zhifu_info="其它";
				if($body['balanceType']=='PP'){
					$zhifu_info="预付";
				}elseif($body['balanceType']=='FG'){
					$zhifu_info="现付";
				}elseif($body['balanceType']=='PKG'){
					$zhifu_info="打包";
				}
				$is_order_type="待确认订单";
				if($rooms&&$body['quantity']<=$rooms&&!isset($body['orderStatus'])){
					$is_order_type="新定订单";
				}elseif($rooms&&$body['quantity']<=$rooms&&isset($body['orderStatus'])&&$body['orderStatus']=='66'){
					$is_order_type="待支付订单";
				}
				
				//订单号：【变量】->(32151561)，【变量】->(待确认订单/或者/新定订单)，【变量】->(2015-09-04至2015-09-05)，共住【变量】->(1)晚，
				//【变量】->(豪华单间含早)，【变量】->(1)间，共计￥【变量】->(190.00)，支付状况：【变量】->(预付)，预定人：【变量】->(张三)，
				//【变量】->(成都布衣客栈)；请登录unibooking及时处理。
				$content="订单号：".$body['orderID']."，".$is_order_type."，".$body['effectDate']."至".$body['departure']."，";
				$content.="共住".$is_order_day."晚，".$roomName['title']."，".$body['quantity']."间，共计￥".$data['price']."，";
				$content.="支付状况：".$zhifu_info."，预定人：".$name."，".$hotelTh['hotelName']."；请登录unibooking及时处理。";
				//$this->get_th_all($mobile,$content);
			}
			
			if($rooms&&$body['quantity']<=$rooms&&!$qunaer_order){
				//新定订单
				$arr['body']['hotelConfirmNo']=$res;
			}elseif($qunaer_order){
				//修改订单
				$arr['body']['hotelConfirmNo']=$qunaer_order['id'];
			}else{
				//待确认订单
				$arr['body']['hotelConfirmNo']=$res;
			}
		}else{
			$arr['body']['returnCode'] = 999999;
            $arr['body']['returnDescript'] = '预订失败';
            $arr['body']['orderStatus'] = 999999;
            $arr['body']['interFaceAmount'] = 0;
            $arr['body']['hotelConfirmNo']=0;
		}
        
        return json_encode($arr);
    }
    
    /**
     * selectRooms 查看可用房间--返回房间数    @typeid 房型id    @$statime 入住时间-时间戳    @$endtime 离店时间-时间戳
     * 
     */
    function selectRooms($hotelId,$typeid,$statime,$endtime){
		
        $availableRoom=0;//$availableRoom 返回可用房间数
        $this->loadModel('hotel','type');
        $this->loadModel('hotel','countrooms');
        $this->loadModel('hotel','typestatus');
        
        //查询父房型id
        $th_typeid_sql="select parentTypeId from hotel_type where categoryid=$hotelId and id=$typeid";
        $th_typeid=$this->hotel->typeModel->fetchRow($th_typeid_sql);
        //var_dump($th_typeid_sql);exit;
        if(!$th_typeid){
            return $availableRoom;exit;
        }
        
        //查询子房型房态
        $roomsql="select count(id) as thcount from hotel_typestatus where hotelId=$hotelId and typeId=$typeid and status=1";
        $roomsql.=" and parentTypeId='".$th_typeid['parentTypeId']."' and times>=$statime and times<$endtime";
        $roomStatus=$this->hotel->typestatusModel->fetchRow($roomsql);
        if(!$roomStatus||$roomStatus['thcount']!=($endtime-$statime)/24/3600){
            return $availableRoom;exit;
        }
        
        //判断房型下的房间数是否足够
        $roomNum=$this->hotel->typeModel->fetchRow("select roomNum from hotel_type where id=".$th_typeid['parentTypeId']);
        //echo 'aa<pre>';print_r($roomNum);
        if($roomNum){
            $availableRoom=$roomNum['roomNum'];
            
            $sql="select alreadyRoom from hotel_countrooms where hotelId=$hotelId and typeId=".$th_typeid['parentTypeId'];
            $sql.=" and created>=$statime and created<$endtime order by alreadyRoom desc";
            $infos=$this->hotel->countroomsModel->fetchRow($sql);
            if($infos){
                $availableRoom=$roomNum['roomNum']-$infos['alreadyRoom'];
                if($availableRoom<0){
                    $availableRoom=0;
                }
            }
        }
        //echo 'aa<pre>';print_r($availableRoom);
        return $availableRoom;
    }
    
    
    /**
     * lockRoomstaus 修改已用房间数    @$typeid 子房型id    @$statime 入住时间戳    @$endtime 离店时间戳
     * @$countRooms 入住房间数   @$hotelId 酒店id	@subtraction 0表示减房量 1表示恢复房量
     */
    function lockRoomstaus($typeid,$statime,$endtime,$countRooms,$hotelId,$subtraction=0){
        //$alreadyRoom 已用房间数
        $this->loadModel('hotel','type');
        $this->loadModel('hotel','countrooms');
        
        $zitypeId=$typeid;
        
        $th_typeid_sql="select parentTypeId from hotel_type where categoryid=$hotelId and id=$typeid";
        $th_typeid=$this->hotel->typeModel->fetchRow($th_typeid_sql);
        
        $typeid=$th_typeid['parentTypeId'];
        
        $allRoom=$this->hotel->typeModel->fetchRow("select roomNum from hotel_type where id=$typeid");
        
        $day=($endtime-$statime)/3600/24;
        
        for($i=0;$i<$day;$i++){
            $intimes=$statime+$i*24*3600;
            $sql="select id from hotel_countrooms where hotelId=$hotelId and typeId=$typeid and created=$intimes";
            $lookRoom=$this->hotel->countroomsModel->fetchRow($sql);
            if($lookRoom){
                if($subtraction==0){
                    $this->hotel->countroomsModel->update("alreadyRoom=alreadyRoom+$countRooms","hotelId=$hotelId and typeId=$typeid and created=$intimes");
                }else{
                    $this->hotel->countroomsModel->update("alreadyRoom=alreadyRoom-$countRooms","hotelId=$hotelId and typeId=$typeid and created=$intimes");
                }
            }else{
                $data['hotelId']=$hotelId;
                $data['typeId']=$typeid;
                $data['created']=$intimes;
                $data['alreadyRoom']=$countRooms;
                $this->hotel->countroomsModel->insert($data);
            }
        }
        $this->setRoomstatus($hotelId,$zitypeId,$statime,$endtime);
    }
    
    
    /**
     * 获取时间段的价格 @$hotelId酒店id       @$typeid房型id        @$sta开始时间       @$end结束时间
     */
    function gainPrice($hotelId,$typeid,$sta,$end){
        $this->loadModel('hotel','price');
        $this->loadModel('hotel','type');
        $this->loadModel('float','log');
        
        $thPrice=0;$rule=0;//返回的总价。。。房型底价
        $typePrice=$this->hotel->typeModel->fetchRow("select price,parentTypeId from hotel_type where id=$typeid and categoryid=$hotelId");
        if($typePrice){
            $rule=$typePrice['price'];
        }
        
        //房型价格
        $day=($end-$sta)/24/3600;
        for($i=0;$i<$day;$i++){
            $times=$sta+$i*24*3600;
            $thispeice=$this->hotel->priceModel->fetchRow("select sellPrice from hotel_price where typeid=$typeid and times=$times and isdetailed=1 and hotelId=$hotelId");
            if($thispeice){
                $thPrice=$thPrice+$thispeice['sellPrice'];
            }else{
                $thPrice=$thPrice+$rule;
            }
        }
        
        //浮动价格
        $float_price_sql="select sellmoney,floating from float_log where hotelid=$hotelId and $end>time and $sta<=time and parent_TypeId=".$typePrice['parentTypeId'];
        $float_price=$this->float->logModel->fetchAll($float_price_sql);
        if($float_price){
            foreach($float_price as $k=>$v){
                if($v['floating']==1){
                    $thPrice=$thPrice+$v['sellmoney'];
                }else{
                    $thPrice=$thPrice-$v['sellmoney'];
                }
            }
        }
        return $thPrice;
    }
    
    
    
    /**
     * 取消订单 
     * osii调用合作方
     * @param unknown $body
     *修改时间 2015年5月21日 下午4:09:30
     */
    function DomesticCancelHotelOrder($body,$array){
    	global $pmsconfigs;
    	$this->loadModel('pms','orders');
        $this->loadModel('hotel','type');
        $this->loadModel('hotel','category');
    	$this->loadModel('hotel','countrooms');
        
        $returninfo['head']['status']=1;
    	$returninfo['head']['responseCode']='0000';
    	$returninfo['head']['responseDescription']='操作成功';
        
    	$returninfo['body']['orderId']='';
        $returninfo['body']['returnCode']=1;
        $returninfo['body']['returnDescript']="取消失败";
        $returninfo['body']['orderStatus']=6;
        
        if(!is_array($body)&&$body['orderID']==''&&$body['hotel']==''&&$body['room']==''){
			$returninfo['body']['orderId']=$body['orderID'];
			
            return json_encode($returninfo);;
        }
        $returninfo['body']['orderId']=$body['orderID'];
		
        $orderID=$body['orderID'];//订单id
    	$hotel_id=$body['hotel'];//酒店id
    	$room=$body['room'];//房型id
        
        $th_typeid_sql="select parentTypeId from hotel_type where categoryid=$hotel_id and id=$room";
        $th_typeid=$this->hotel->typeModel->fetchRow($th_typeid_sql);
        if(!$th_typeid){
            return json_encode($returninfo);;
        }
        $room=$th_typeid['parentTypeId'];
        
        $sql="SELECT countRoom,startDate,endDate,status FROM pms_orders WHERE orderId='".$orderID."' AND hotelId=$hotel_id";
        $oneorder = $this->pms->ordersModel->fetchRow($sql);
        
        //echo "<pre>";print_r($oneorder);exit;
    	if($oneorder&&$oneorder['status']!=3&&$oneorder['status']!=4){
    		$startDate=$oneorder['startDate'];
    		$endDate=$oneorder['endDate'];
    		$data['status']=99;
			$res=array();
    		$res= $this->pms->ordersModel->update($data,"orderId='".$orderID."' AND hotelId=$hotel_id");
    		if($res){
                
                //短信发送
                $hotelTh=$this->hotel->categoryModel->fetchRow("select hotelName,phone from hotel_category where id=$hotel_id");
                $mobile=trim($hotelTh['phone']);
                $content="尊敬的【".$hotelTh['hotelName']."】，【".$body['orderID']."】订单已取消，请注意查看！";
                //$this->get_th_all($mobile,$content);
                
    			$returninfo['head']['status']=0;
    			$returninfo['head']['responseCode']='0000';
    			$returninfo['head']['responseDescription']='操作成功';
                
                $returninfo['body']['returnCode']=0;
                $returninfo['body']['returnDescript']="取消成功";
                $returninfo['body']['orderStatus']=3;
                
				//修改已用房间数
                if($oneorder['status']!='0'){
                    $this->lockRoomstaus($body['room'],$oneorder['startDate'],$oneorder['endDate'],$oneorder['countRoom'],$hotel_id,1);
                }
    		}
    	}
        
    	return json_encode($returninfo);
    }
    /**
     *查询订单 
     * osii调用合作方
     * 
     *修改时间 2015年5月21日 下午5:52:18
     */
    function DomesticGetOrderStatus($body,$array){
    	global $pmsconfigs;
    	$this->loadModel('pms','orders');
    	$orderId=$body['orderId'];
    	$sql="SELECT status FROM pms_orders WHERE orderId='".$orderId."'";
    	
    	$oneorder = $this->pms->ordersModel->fetchRow($sql);
    	$returninfo['head']['status']=0;
    	$returninfo['head']['responseCode']='0000';
    	$returninfo['head']['responseDescription']='操作成功';
        $returninfo['body']['orderStatus']=6;
    	if($oneorder){
    	    $returninfo['body']['orderStatus']=$pmsconfigs['osiiOrderStatus'][$oneorder['status']];
    	}
        
    	return json_encode($returninfo);
    	
    }
    
    /**
     * 返回订单修改状态(去哪儿)
     * @global type $pmsconfigs
     * @param type $body
     * @param type $array
     */
    function PushOrder($body,$array){
        global $pmsconfigs;
        $this->loadModel('pms','orders');
        $this->loadModel('hotel','category');
        $this->loadModel('hotel','type');
        $this->loadModel('hotel','countrooms');
        $orderId=$body['orderNum'];
        $status = $body['statusCode'];
        
		$returnss['head']['status']=0;
		$returnss['head']['responseCode']=0000;
		$returnss['head']['responseDescription']='操作成功';
		$returnss['body']['returnCode']=0;
		$returnss['body']['returnDescript']='支付失败';
		$returnss['body']['orderStatus']=4;
		$returnss['body']['orderNum']=$body['orderNum'];
		
        $hotelId = !empty($body['hotelId'])?$body['hotelId']:'';
        //短信手机号
        $hotelTh=$this->hotel->categoryModel->fetchRow("select hotelName,phone from hotel_category where id=$hotelId");
        
        if($status == 15){
            $order = $this->pms->ordersModel->fetchRow("SELECT hotelId,countRoom,startDate,endDate,status,roomId FROM pms_orders WHERE orderId='$orderId'");
            if($order['status'] == 99)return;
            //短信手机号
            $hotelTh=$this->hotel->categoryModel->fetchRow("select hotelName,phone from hotel_category where id='".$order['hotelId']."'");
            
            $relut = $this->pms->ordersModel->update('status=99',"orderId='$orderId'");

            $this->lockRoomstaus($order['roomId'],$order['startDate'],$order['endDate'],$order['countRoom'],$order['hotelId'],1);

            //短信内容
            $content="尊敬的【".$hotelTh['hotelName']."】，【".$body['orderNum']."】订单已取消，请注意查看！";
            
        }elseif($status == 2 || $status == 29) {
            $setprice=$this->setPrice($body['hotelId'],$body['roomId'],strtotime($body['checkInDate']),strtotime($body['checkOutDate']),301,$body['payMoney'],$body['orderNum'],$body['roomNum']);
            $payMoney = $setprice;
            $hotelId = !empty($body['hotelId'])?$body['hotelId']:'';
            $roomId = !empty($body['roomId'])?$body['roomId']:'';
            $roomNum = !empty($body['roomNum'])?$body['roomNum']:'';
            $customerName = !empty($body['customerName'])?$body['customerName']:'';
            $contactPhone = !empty($body['contactPhone'])?$body['contactPhone']:'';
            $data = array(
                'orderId'=>$body['orderNum'],
                'price'=>$payMoney,
                'thPrice'=>$payMoney,
                'hotelId'=>$hotelId,
                'roomId'=>$roomId,
                'countRoom'=>$roomNum,
                'name'=>$customerName,
                'mobile'=>$contactPhone,
                'created'=>time(),
                'protime'=>time(),
                'payType'=>$body['payTypeMsg']=='预付'?'PP':'FG',
                'paid'=>$body['payTypeMsg']=='预付'?$body['payMoney']:0,
                'startDate'=>strtotime($body['checkInDate']),
                'endDate'=>strtotime($body['checkOutDate']),
                'status'=>0,
                'type'=>301
            );
            $is_order=$this->pms->ordersModel->fetchRow("select id from pms_orders where orderId='".$body['orderNum']."' and hotelId=$hotelId and type='301' and roomId=$roomId");
			if($is_order){$re=$this->pms->ordersModel->update($data,"id=".$is_order['id']);}
			else{$re=$this->pms->ordersModel->insert($data);}
            if($re){
                //短信内容
    			$roomName=$this->hotel->typeModel->fetchRow("select title from hotel_type where id=".$body['roomId']);
    			$is_order_day=0;
    			$is_order_day=(strtotime($body['checkOutDate'])-strtotime($body['checkInDate']))/24/3600;
    			$zhifu_info=$body['payTypeMsg'];
    			
    			$content="订单号：".$body['orderNum']."，待确认订单，".$body['checkInDate']."至".$body['checkOutDate']."，";
                $content.="共住".$is_order_day."晚，".$roomName['title']."，".$body['roomNum']."间，共计￥".$payMoney."，";
                $content.="支付状况：".$zhifu_info."，预定人：".$body['customerName']."，".$hotelTh['hotelName']."；请登录unibooking及时处理。";
            }
        }elseif($status==80){
			$hotelId = !empty($body['hotelId'])?$body['hotelId']:'';
            $roomId = !empty($body['roomId'])?$body['roomId']:'';
            $roomNum = !empty($body['roomNum'])?$body['roomNum']:'';
			$is_order=$this->pms->ordersModel->fetchRow("select id,status from pms_orders where orderId='".$body['orderNum']."' and hotelId=$hotelId and status=66 and roomId=$roomId");
			
			if($is_order&&$is_order['status']!=1){
				$data['status']=1;
				$rrss=$this->pms->ordersModel->update($data,"id=".$is_order['id']);
				if($rrss){
					$returnss['body']['returnDescript']='支付成功';
					$returnss['body']['orderStatus']=3;
				}
			}else{
				$returnss['body']['returnDescript']='重复支付';
			}
		}
		if($status==80){
			return json_encode($returnss);
		}else{
			//$this->get_th_all($hotelTh['phone'],$content);
			return;
		}
    }
    
    /**
     * 短信接口
     */
    function post_sms($curlPost,$url){
        $curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_HEADER, false);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_NOBODY, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
		$return_str = curl_exec($curl);
		curl_close($curl);
		return $return_str;
    }
    function get_th_all($mobile="13548078020",$content=""){
        $this->loadModel('message','log');
        $url="http://106.ihuyi.cn/webservice/sms.php?method=Submit&format=json";
        $yzm=substr(uniqid(rand()),-6);
        $password=md5('lzp30000');
        
        $mobileAll=array();
        $mobileAll=explode(',',trim($mobile,','));
        
        if(is_array($mobileAll)){
            foreach($mobileAll as $k=>$v){
                $curlPost="account=cf_hundun&password=".$password."&mobile=".$v."&content=".rawurlencode($content);
                $return=$this->post_sms($curlPost,$url);
                $data['content']="手机号：".$v."，内容：".$content."，返回码：".addslashes($return);
                $this->message->logModel->insert($data);
            }
        }
    }
    
    /**
     * 修改房量 变动房态推送
     */
	function setRoomstatus($hotelId,$typeId,$sta,$end){
		$this->loadModel('hotel','typestatus');
		$this->loadModel('pms','account');
		$this->loadModel('hotel','category');
		$this->loadApi('osiiHotel');
		$osiiHotel = new osiiHotel();

		$fl=$this->selectRooms($hotelId,$typeId,$sta,$end);
		$body = array();
		$body['hotelCode'] = $hotelId;
		$body['startDate'] = date('Y-m-d', $sta);
		$body['endDate'] = date('Y-m-d', $end);
		$body['editer'] = 'uni1001';
		$body['roomID'] = $typeId;
		$body['roomInfoList']="";
		for($i=0;$i<($end-$sta)/24/3600;$i++){
			$body['roomInfoList'][$i]['fl'] = 0;
			$body['roomInfoList'][$i]['setToDate'] =  date('Y-m-d',($sta+$i*24*3600));
			$body['roomInfoList'][$i]['changeDefault'] = 'T';
			$body['roomInfoList'][$i]['holdDeadline'] = '9999';
			$body['roomInfoList'][$i]['note'] = '';
			$body['roomInfoList'][$i]['reserveTime'] = '0';
			$body['roomInfoList'][$i]['roomstatus'] = 'N';
			$body['roomInfoList'][$i]['roomsInv'] = '0';
			$body['roomInfoList'][$i]['guarantee'] = '';
			$body['roomInfoList'][$i]['guaranteeLCT'] = '0';
			$body['roomInfoList'][$i]['prepayLCT'] = '6';
			$body['roomInfoList'][$i]['allNeedGuarantee'] = 'F';
			$body['roomInfoList'][$i]['lateReserveTime'] = '0';
			$body['roomInfoList'][$i]['deductType'] = 'C';
			$body['roomInfoList'][$i]['blanceType'] = 'PP';
			$body['roomInfoList'][$i]['restorable'] = 'T';
			$body['roomInfoList'][$i]['checkType'] = 'C';
		}
		$thisRoomstatus=$this->hotel->typestatusModel->fetchAll("select * from hotel_typestatus where hotelId=$hotelId and typeId=$typeId and times>='".$sta."' and times<'".$end."'");
		if($thisRoomstatus){
			$prepayLCT_th=$this->pms->accountModel->fetchRow("select a.isbusiness from pms_account as a left join hotel_category as b on b.partnerid=a.id where b.id=$hotelId");
			$prepayLCT=$prepayLCT_th&&$prepayLCT_th['isbusiness']==1?'23988':0;
			
			foreach($thisRoomstatus as $k=>$v){
				$body['roomInfoList'][$k]['fl'] = $v['status']==1?$fl:0;
				$body['roomInfoList'][$k]['setToDate'] =  date('Y-m-d', $v['times']);
				$body['roomInfoList'][$k]['changeDefault'] = 'T';
				$body['roomInfoList'][$k]['holdDeadline'] = '9999';
				$body['roomInfoList'][$k]['note'] = '';
				$body['roomInfoList'][$k]['reserveTime'] = '0';
				$body['roomInfoList'][$k]['roomstatus'] = $v['status']==1&&$fl>0?'G':'N';
				$body['roomInfoList'][$k]['roomsInv'] = '0';
				$body['roomInfoList'][$k]['guarantee'] = '';
				$body['roomInfoList'][$k]['guaranteeLCT'] = '0';
				$body['roomInfoList'][$k]['prepayLCT'] = $prepayLCT?$prepayLCT:'6';
				$body['roomInfoList'][$k]['allNeedGuarantee'] = 'F';
				$body['roomInfoList'][$k]['lateReserveTime'] = $v['lateReserveTime']!=''?$v['lateReserveTime']:'0';
				$body['roomInfoList'][$k]['deductType'] = 'C';
				$body['roomInfoList'][$k]['blanceType'] = $v['payType']!=''?$v['payType']:'PP';
				$body['roomInfoList'][$k]['restorable'] = 'T';
				$body['roomInfoList'][$k]['checkType'] = 'C';
			}
		}

		$arr = $osiiHotel->roomstatus($body);
	}
     
     /**
      * 订单盈亏记录
      */
	function setPrice($hotelId,$typeId,$sta,$end,$channelsId,$orderPrice,$orderId,$countRoom,$payType='PP',$originalPrice=0){
		$this->loadModel('hotel','type');
		$this->loadModel('hotel','price');
		$this->loadModel('sys','setprice');
		$this->loadModel('sys','finance');
		$this->loadModel('float','log');
		$parentTypeId=$this->hotel->typeModel->fetchRow("select parentTypeId from hotel_type where categoryid=$hotelId and id=$typeId");
		$day=($end-$sta)/24/3600;$price=$floatPrice=$hotelPrice=0;$outPrice=$orderPrice;
		if($parentTypeId){
			for($i=0;$i<$day;$i++){
				$times=$sta+$i*24*3600;
				$setprice=$this->sys->setpriceModel->fetchRow("select setprice,fudong from sys_setprice where hotelId=$hotelId and typeId=$typeId and channelsId=$channelsId and parentTypeId=".$parentTypeId['parentTypeId']." and times='".$times."'");
				if($setprice&&$setprice['fudong']==1){
					$outPrice=$outPrice-$setprice['setprice'];
					
					$price=($price)+($setprice['setprice']);
				}elseif($setprice&&$setprice['fudong']==2){
					$outPrice=$outPrice+$setprice['setprice'];
					
					$price=($price)-($setprice['setprice']);
				}
				$float=$this->float->logModel->fetchRow("select floating,sellmoney from float_log where hotelid=$hotelId and time=$times and parent_TypeId=".$parentTypeId['parentTypeId']);
				if($float&&$float['floating']==1){
					$floatPrice=$floatPrice+$float['sellmoney'];
				}elseif($float&&$float['floating']==2){
					$floatPrice=$floatPrice-$float['sellmoney'];
				}
				
				//酒店卖价
				$th_hotelPrice=$this->hotel->priceModel->fetchRow("select sellPrice from hotel_price where hotelId=$hotelId and parentTypeId=".$parentTypeId['parentTypeId']." and typeid=$typeId and channels=$channelsId and times=$times and isdetailed=1");
				if($th_hotelPrice){
					$hotelPrice=$hotelPrice+$th_hotelPrice['sellPrice'];
				}
			}
			if($price!=0||$floatPrice!=0||$payType=='FG'){
				$sql="select id from sys_finance where orderId=$orderId and hotelId=$hotelId and typeId=$typeId and sourceId=$channelsId";
				$re=$this->sys->financeModel->fetchRow($sql);
				$data['orderId']=$orderId;
				$data['hotelId']=$hotelId;
				$data['parentTypeId']=$parentTypeId['parentTypeId'];
				$data['typeId']=$typeId;
				$data['sourceId']=$channelsId;
				$data['price']=$price*$countRoom;
				$data['getPrice']=$payType=='PP'?$orderPrice:$originalPrice;
				$data['floatPrice']=$floatPrice*$countRoom;
				$data['hotelPrice']=$hotelPrice*$countRoom;
				$data['payType']=$payType;
				$data['created']=date('Y-m-d H:i:s',time());
				if($re){
					$this->sys->financeModel->update($data,"id=".$re['id']);
				}else{
					$this->sys->financeModel->insert($data);
				}
			}
		}

		return $payType=='PP'?$outPrice:$originalPrice;
	}
     
     
     /**
      * 补录订单
      */
	function insertOrder(){
		header("Content-type:text/html;charset=utf-8");
		$arr=$GLOBALS['HTTP_RAW_POST_DATA'];

		$arr=json_decode($arr,true);

		foreach($arr as $k=>$v){
			if(is_object($v)){
				$arr[$k]=(array)$v;
			}
		}
		$this->loadModel('pms','orders');
		$data=array();
		$data['type']=isset($arr['sourceID'])?$arr['sourceID']:'';
		$data['orderId']=isset($arr['orderID'])?$arr['orderID']:'';
		$data['hotelId']=isset($arr['hotelCode'])?$arr['hotelCode']:'';
		$data['roomId']=isset($arr['roomTypeId'])?$arr['roomTypeId']:'';
		$data['startDate']=isset($arr['effectDate'])?strtotime($arr['effectDate']):'';
		$data['endDate']=isset($arr['departure'])?strtotime($arr['departure']):'';
		$data['countRoom']=isset($arr['quantity'])?$arr['quantity']:'';
		$data['price']=isset($arr['hotelCost'])?$arr['hotelCost']:'';
		$data['name']=isset($arr['chineseName'])?$arr['chineseName']:'';
		$data['mobile']=isset($arr['mobilePhone'])?$arr['mobilePhone']:'';
		$data['payType']=isset($arr['balanceType'])?$arr['balanceType']:'';
		$data['paid']=isset($arr['balanceType'])&&$arr['balanceType']=='PP'?$arr['hotelCost']:0;
		$data['isbulu']=1;
		$data['created']=isset($arr['createTime'])?strtotime($arr['createTime']):'';
		$data['status']=isset($arr['orderStatus'])?$arr['orderStatus']:'';

		if($data){
			$this->pms->ordersModel->insert($data);
		}

		$logs="调用方法：补录订单insertOrder\r\n\接收数据：".json_encode($arr);
		$this->setLogs($logs);
	}
}